import { useApi } from '@/composables/useApi';
import { useRouter } from 'vue-router';
import type { SiteData, DatabaseTypes } from '~/types/home';


export const useHomeApi = () => {
  const router = useRouter()

  // 统一错误处理 (与useHomeApi保持一致)
  // const handleError = (error: any) => {
  //   const message = error.data?.message || error?.message || 'Request failed'
  //   const code = error.statusCode || 500

  //   // 显示错误提示（可根据UI库调整）
  //   console.error(`[PageApi Error] ${message}`)

  //   // 401 未授权跳转到登录页
  //   if (code === 401) {
  //     router.push('/login')
  //   }

  //   // 抛出格式化后的错误
  //   throw {
  //     code,
  //     message,
  //     data: error.data?.data || null
  //   }
  // }

  // 获取首页聚合数据
  const getHomeData = async (): Promise<DatabaseTypes> => {
    try {
      const response = await useApi<SiteData>('/api/page-data', {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      console.log('Home data fetched successfully:', response)
      // 转换数据格式以适应前端组件
      return response.data
      // return {
      //   banner: data.banner || {
      //     companyName: '',
      //     slogan: '',
      //     logo: '',
      //     gradient: ''
      //   },
      //   services: data.services || [],
      //   cases: data.cases || [],
      //   team: data.team || [],
      //   partners: data.partners || []
      // }
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }
  const updateHomeData = async (data: DatabaseTypes) => {
    try {
      const response = await $fetch<SiteData>('/api/page-data', {
        method: 'PUT',
        body: data,
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.success) {
        console.log('首页数据更新成功:', response)
        // 可以在这里添加成功通知
        return response
      }

      throw new Error(response.message || '更新失败')

    } catch (error) {
      console.error('更新首页数据失败:', error)
      throw error // 继续抛出错误以便外部处理
    }
  }

  const contactSubmit = async (formData: any) => {
    try {
      const response = await useApi<any>('/api/contact', {
        method: 'POST',
        body: JSON.stringify(formData),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      console.log('Form submitted successfully:', response)
      // 处理提交成功后的逻辑
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  return {
    getHomeData,
    updateHomeData,
    contactSubmit
  }
}